package com.example.lib.utils

import android.app.Activity
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.location.LocationManager
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.example.lib.LibApp
import java.util.Timer
import kotlin.concurrent.timerTask


object AppUtils {
    private val timer = Timer()

    fun getVersionName(): String {
        val packageManager = LibApp.appContext.packageManager
        val flag = 0
        var packageInfo: PackageInfo? = null
        try {
            packageInfo = packageManager.getPackageInfo(LibApp.appContext.packageName, flag)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return packageInfo?.versionName ?: ""
    }

    /**
     * 显示
     */
    fun showInputKey(activity: Activity, view: View) {
        timer.schedule(timerTask {
            activity.runOnUiThread {
                getInputKeyState(activity)?.let {
                    view.requestFocus()
                    it.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
                }
            }
        }, 300)
    }

    /**
     * 收起软键盘
     */
    fun packUpInputKey(activity: Activity) {
        getInputKeyState(activity)?.hideSoftInputFromWindow(activity
            .currentFocus?.windowToken, 0)
    }

    /**
     * 获取软键盘显示状态
     */
    private fun getInputKeyState(context: Context): InputMethodManager? {
        return context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    }

    fun isOpenLocation(): Boolean {
        val locationManager = LibApp.appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager?
        return locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER) == true
    }
}